<?php
/**
    fb_sync v0.1.1
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    This file is part of the fbpost package. 
    
    fbpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    fbpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with fbpost. If not, see <http://www.gnu.org/licenses/>. 
**/

require_once(dirname(__FILE__)."/inc/common.php");

$addon_name = "fb_sync<a name='fb_sync'></a>";
$addon_version = "0.1.1";
$addon_description = "Adds the new item <em>FB_SYNC</em> to the image/edit "
    . "section of the Pixelpost admin interface, which allows posting "
    . "updates (as wall posts) about your Pixelpost photos to any Facebook "
    . "profile you have administrative access to. <br />"
    . "Full-res photos will <em>not</em> be uploaded to Facebook - only "
    . "thumbnails. <br />";

// don't do anything if plugin is disabled
if (!isAddonEnabled("admin_fb_sync")) return;

$errormsg = '';
try {
    checkExtensions();
} catch (Exception $e) {
    $errormsg .= $e->getMessage() . "\n";
}

// populate variables from config table
$result = mysql_query("SELECT * FROM " . TABLE_FBPOST_CFG . " LIMIT 1") 
    or $errormsg .= "Could not retrieve default configuration: " . mysql_error() . "<br />";
while ($row = mysql_fetch_array($result)) {
    $def_profile_id = $row["def_profile_id"];
    $def_sync_message = $row["def_sync_message"];
}
$GLOBALS['FB_DEF_PROFILE_ID'] = $def_profile_id;
$GLOBALS['FB_DEF_SYNC_MESSAGE'] = $def_sync_message;

// process POST requests (store updated configuration)
if (isset($_POST['fb_sync_do'])) {
    if ($_POST['fb_sync_do'] == 'config') {
        $def_profile_id = $_POST['def_profile_id'];
        $def_sync_message = $_POST['def_sync_message'];
        mysql_query("UPDATE " . TABLE_FBPOST_CFG . " SET " . 
                    "def_profile_id='$def_profile_id', " . 
                    "def_sync_message='$def_sync_message'") or die(mysql_error());
        $_SESSION['fb_sync_result'] = 'Configuration saved. ';
    }
}

// addon admin page
if (isset($_GET['view']) and $_GET['view']=='addons') {
    if (isset($_SESSION['fb_sync_result'])) {
        $addon_description .= "<em>" . $_SESSION['fb_sync_result'] . '</em><hr />';
        unset($_SESSION['fb_sync_result']);
    }
    if (isset($errormsg) and $errormsg != "") {
        $addon_description .= formatErrorMsg($errormsg);
    }
    else {
        // retrieve target profile IDs from FB
        $fbproxy = new FBProxy();
        $profiles = array();
        try {
            $profiles = $fbproxy->getProfiles();
        } catch (FBApiException $e) {
            $addon_description .= formatErrorMsg($e->getMessage());
        }
        
        $addon_description .= <<<EOT
            <p><strong>Configuration</strong></p>
            <form action='{$cfgrow['siteurl']}admin/index.php?view=addons#fb_sync' method='post' accept-charset='UTF-8'>
                <input type='hidden' name='fb_sync_do' value='config' />
                <table>
                    <tr style='vertical-align:top;'>
                        <td>Post on this profile by default: </td>
                        <td>
                            <select name='def_profile_id'>
EOT;
            foreach ($profiles as $id => $data) {
                $selected = ($def_profile_id == $id) ? "selected='selected'" : "";
                $addon_description .= "<option value='{$id}' {$selected}>{$data["name"]}</option>";
            }
            $addon_description .= <<<EOT
                            </select>
                        </td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Default message for wall posts: </td>
                        <td><input type='text' size='40' name='def_sync_message' value='{$def_sync_message}' /></td>
                    </tr>
                </table>
                <input type='submit' value='Save' />
            </form>
EOT;
    }
}


// only add image_edit function if required PHP extensions are available
try {
    checkExtensions();
    add_admin_functions('fb_sync_image_edit', 'image_edit', 'images', 'fb_sync');
} catch (Exception $e) {
    // nothing - function has not been added
}
function fb_sync_image_edit()
{
    require_once('../includes/markdown.php');  // required to strip markup from description
    global $cfgrow, $image;
    $def_profile_id = $GLOBALS["FB_DEF_PROFILE_ID"];
    $img_id = $_GET['id'];
    $img_url = $cfgrow['imagepath'] . $image;
    $post_url = $cfgrow['siteurl'] . "index.php?showimage=$img_id";
    $thumb_url = $cfgrow['siteurl'] . ltrim($cfgrow['thumbnailpath'], "./") . "thumb_" . $image;
    
    // initialize default parameters: 
    $profile_id = $def_profile_id;
    $message = $GLOBALS["FB_DEF_SYNC_MESSAGE"];
    $name = $GLOBALS["headline"];
    $caption = " ";
    $desc = trim(strip_tags(markdown($GLOBALS["body"])));
    
    // retrieve POST params
    if (isset($_POST['do']) and $_POST['do'] == "post") {
        foreach (array("profile_id", "message", "name", "caption", "desc") as $var) {
            if (isset($_POST[$var]) and get_magic_quotes_gpc())
                $_POST[$var] = stripslashes($_POST[$var]);
            $$var = isset($_POST[$var]) ? $_POST[$var] : $$var;
        }
    }
    
    // initialize FB proxy object and get account/profile data
    $fbproxy = new FBProxy();
    $profiles = array();
    try {
        $profiles = $fbproxy->getProfiles();
    } catch (FBApiException $e) {
        echo formatErrorMsg($e->getMessage());
        return;
    }
    $profile = getVal($fbproxy->getProfiles(), $profile_id);
    
    echo "<div class='content'>";
    if (isset($_POST['do']) and $_POST['do'] == "post") {
        // if post has a link and/or a picture, it needs a caption (otherwise 
        // the hostname is displayed as the caption) (but whitespace works)
        $args = array("link" => $post_url, 
                      "message" => $message, 
                      "picture" => $thumb_url, 
                      "name" => $name, 
                      "caption" => $caption, 
                      "description" => $_POST['desc'], 
                      "access_token" => getval($profile, "access_token"));
        $result = $fbproxy->api("/$profile_id/feed", $args, "POST");
        $profile_url = "http://www.facebook.com/profile.php?id=$profile_id";
        echo "Successfully created a wall post on <a href='$profile_url'>{$profile["name"]}</a> (ID " . $result["id"] . ")";
    }
    else {
        echo <<<EOT
            Modify the parameters as desired, then hit the button to post <strong><a href='$img_url'>$image</a></strong> [ID#$img_id] to the selected profile: 
            <hr />
            <form action='{$_SERVER["REQUEST_URI"]}' method='post'>
                <input type='hidden' name='do' value='post' />
                <table>
                    <tr style='vertical-align:top;'>
                        <td>Post to: </td>
                        <td>
                            <select name='profile_id'>
EOT;
        foreach ($profiles as $id => $data) {
            $selected = ($def_profile_id == $id) ? "selected='selected'" : "";
            echo "<option value='{$id}' {$selected}>{$data["name"]}</option>";
        }
        echo <<<EOT
                            </select>
                        </td>
                        <td rowspan='5' style='text-align:right;'>
                            <img src='$thumb_url' />
                            <br /><br />
                            <input type='submit' value='Post' />
                        </td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Message: </td>
                        <td><input type='text' style='width:98%;' name='message' value='{$message}' /></td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Name: </td>
                        <td><input type='text' style='width:98%;' name='name' value='{$name}' /></td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Caption: <br /><span style="font-size:0.8em;">(leave " " for no caption)</span>
                        </td>
                        <td><input type='text' style='width:98%;' name='caption' value='{$caption}' /></td>
                    </tr>
                    <tr style='vertical-align:top;'>
                        <td>Description: </td>
                        <td><textarea type='text' rows='5' cols='50' name='desc'>{$desc}</textarea></td>
                    </tr>
                </table>
            </form>
EOT;
    }
    echo "</div>";
}
?>
